package com.mr.cai.main.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.mr.cai.main.R;

/**
 * Created by hai8108 on 15/11/23.
 */
public class LineEditText extends EditText implements TextWatcher,
        View.OnFocusChangeListener {
    private Paint mPaint;
    private int bottomLineColor;
    private int textColor;
    public static final int STATUS_FOCUSED = 1;
    public static final int STATUS_UNFOCUSED = 2;
    public static final int STATUS_ERROR = 3;
    private int status = 2;
    private Drawable del_btn;
    private Drawable del_btn_down;
    private int focusedDrawableId = R.drawable.user_select;// 默认的
    private int unfocusedDrawableId = R.drawable.user;
    private int errorDrawableId = R.drawable.user_error;
    Drawable left = null;
    private Context mContext;
    /**
     * 是否获取焦点，默认没有焦点
     */
    private boolean hasFocus = false;
    /**
     * 手指抬起时的X坐标
     */
    private int xUp = 0;
    public LineEditText (Context context) {
        super(context);
        mContext = context;
        init();
    }
    public LineEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }
    public LineEditText (Context context, AttributeSet attrs, int defStryle) {
        super(context, attrs, defStryle);
        mContext = context;
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.lineEdittext, defStryle, 0);
        focusedDrawableId = a.getResourceId(
                R.styleable.lineEdittext_drawableFocus, R.drawable.user_select);
        unfocusedDrawableId = a.getResourceId(
                R.styleable.lineEdittext_drawableUnFocus, R.drawable.user);
        errorDrawableId = a.getResourceId(
                R.styleable.lineEdittext_drawableError, R.drawable.user_error);
        bottomLineColor = a.getColor(R.styleable.lineEdittext_bottomLineColor, mContext
                .getResources().getColor(R.color.color_main_green));
        a.recycle();
        init();
    }
    public void setBottomLineColor(@ColorRes int resColorId){
        bottomLineColor = mContext.getResources()
                .getColor(resColorId);
        invalidate();
    }
    /**
     * 2014/7/31
     *
     * @author Aimee.ZHANG
     */
    private void init() {
        mPaint = new Paint();
        // mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(3.0f);
        bottomLineColor = mContext.getResources().getColor(R.color.color_main_green);
        setStatus(status);
        del_btn = mContext.getResources().getDrawable(R.drawable.del_btn_bg);
//        del_btn_down = mContext.getResources().getDrawable(R.drawable.del_but_bg_down);
        del_btn_down = mContext.getResources().getDrawable(R.drawable.del_btn_bg);
        addListeners();
        setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(bottomLineColor);
        int x=this.getScrollX();
        int w=this.getMeasuredWidth();
        canvas.drawLine(0, this.getHeight() - 1, w+x,
                this.getHeight() - 1, mPaint);   //画editText最下方的线
    }

    // 处理删除事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (del_btn != null && event.getAction() == MotionEvent.ACTION_UP) {
            // 获取点击时手指抬起的X坐标
            xUp = (int) event.getX();
            /*Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 50;*/
            // 当点击的坐标到当前输入框右侧的距离小于等于getCompoundPaddingRight()的距离时，则认为是点击了删除图标
            if ((getWidth() - xUp) <= getCompoundPaddingRight()) {
                if (!TextUtils.isEmpty(getText().toString())) {
                    setText("");
                }
            }
        }else if(del_btn != null && event.getAction() == MotionEvent.ACTION_DOWN && getText().length()!=0){
            setCompoundDrawablesWithIntrinsicBounds(left,null,del_btn_down,null);
        }else if(getText().length()!=0){
            setCompoundDrawablesWithIntrinsicBounds(left,null,del_btn,null);
        }
        return super.onTouchEvent(event);
    }
    public void setStatus(int status) {
        this.status = status;
        if (status == STATUS_ERROR) {
//            try {
//                left = getResources().getDrawable(errorDrawableId);
//            } catch (Resources.NotFoundException e) {
//                e.printStackTrace();
//            }
            setColor(mContext.getResources().getColor(R.color.color_main_red));
        } else if (status == STATUS_FOCUSED) {
//            try {
//                left = getResources().getDrawable(focusedDrawableId);
//            } catch (Resources.NotFoundException e) {
//                e.printStackTrace();
//            }
            setColor(mContext.getResources().getColor(R.color.color_main_sub_white_gray));
        } else {
//            try {
//                left = getResources().getDrawable(unfocusedDrawableId);
//            } catch (Resources.NotFoundException e) {
//                e.printStackTrace();
//            }
            setColor(mContext.getResources().getColor(R.color.color_main_sub_white_gray));
        }
//        if (left != null) {
            //setCompoundDrawablesWithIntrinsicBounds(left,null,null,null);
//        }
        postInvalidate();
    }
    public void setLeftDrawable(int focusedDrawableId, int unfocusedDrawableId,
                                int errorDrawableId) {
        this.focusedDrawableId = focusedDrawableId;
        this.unfocusedDrawableId = unfocusedDrawableId;
        this.errorDrawableId = errorDrawableId;
        setStatus(status);
    }
    private void addListeners() {
        try {
            setOnFocusChangeListener(this);
            addTextChangedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onFocusChanged(boolean focused, int direction,
                                  Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        this.hasFocus=focused;
        if (focused) {
            setStatus(STATUS_FOCUSED);
        } else {
            setStatus(STATUS_UNFOCUSED);
            setCompoundDrawablesWithIntrinsicBounds(left,null,null,null);
        }
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    };
    public void setColor(int color) {
        this.textColor = color;
        this.setTextColor(textColor);
        invalidate();
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub
        postInvalidate();
    }
    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
        // TODO Auto-generated method stub
        if (TextUtils.isEmpty(arg0)) {
            // 如果为空，则不显示删除图标
            setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
        } else {
            // 如果非空，则要显示删除图标
            setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null);
        }
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int after) {
        if (hasFocus) {
            if (TextUtils.isEmpty(s)) {
                // 如果为空，则不显示删除图标
                setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
            } else {
                // 如果非空，则要显示删除图标
                setCompoundDrawablesWithIntrinsicBounds(left, null, del_btn, null);
                //EditText输入手机号自动带空格
                // 当长度为3或8时我们会添加一个" "，当碰到空格时会默认调整光标的位置。
//                if (s == null || s.length() == 0) {
//                      return;
//                   }
//                StringBuilder sb = new StringBuilder();
//                for (int i = 0; i < s.length(); i++) {
//                    if (i != 3 && i != 8 && s.charAt(i) == ' ') {
//                        continue;
//                    } else {
//                        sb.append(s.charAt(i));
//                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
//                            sb.insert(sb.length() - 1, ' ');
//                        }
//                    }
//                }
//                if (!sb.toString().equals(s.toString())) {
//                    int index = start + 1;
//                    if (sb.charAt(start) == ' ') {
//                        if (before == 0) {
//                            index++;
//                        } else {
//                            index--;
//                        }
//                    } else {
//                        if (before == 1) {
//                            index--;
//                        }
//                    }
//                    setText(sb.toString());
//                    setSelection(index);
//                }
            }
        }
    }
    @Override
    public void onFocusChange(View arg0, boolean arg1) {
        // TODO Auto-generated method stub
        try {
            this.hasFocus = arg1;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
